<template>
  <div class="vue-box" style="display: none;" :style="'display: block;'">
    <el-dialog v-bind="$attrs"
               :visible.sync="dialogVisible"
               :append-to-body="true"
               :close-on-click-modal="false"
               v-on="$listeners" @open="onOpen" @close="onClose" :title="dialogTitle">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="100px">
          <el-col :span="24">
            <el-form-item label="上级区域" prop="pid">
              <el-cascader v-model="formData.pid" :options="pidOptions" :props="pidProps"
                           :disabled="disFlag"
                           :style="{width: '100%'}" placeholder="请选择上级区域" filterable clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入区域名称" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理人姓名" prop="manage">
              <el-input v-model="formData.manage" placeholder="请输入管理人姓名" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理人号码" prop="managePhone">
              <el-input v-model="formData.managePhone" placeholder="请输入管理人号码" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" placeholder="排序" :step='1'></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status" required>
              <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注或说明" prop="remark">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注或说明"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>

    <div class="c-panel">
      <!-- ------------- 检索参数 ------------- -->
      <!-- ------------- 快捷按钮 ------------- -->
      <el-row :gutter="15">
        <el-col :span="10">
          <div class="c-title">区域管理<span style="float: right;font-size: small"
                                             title="关闭此按钮只会查看当前区域下的信息不会递归查询子集">
            是否查看子集
            <el-switch v-model="showChildren"></el-switch>
          </span></div>
          <el-form :inline="true" @submit.native.prevent>
            <el-button type="primary" @click="dialogVisible = true;dialogTitle='新增机构';disFlag=false">新增
            </el-button>
            <el-button type="success" v-show="!expandAll" @click="setAllExpand">展开</el-button>
            <el-button type="info" v-show="expandAll" @click="setAllFold">收起</el-button>
            <el-input
                placeholder="输入关键字进行过滤"
                v-model="regionKey"
                clearable>
            </el-input>
          </el-form>
          <div style="height: calc(100vh - var(--nav-right-1-height) - var(--nav-right-2-height) - 40px);
          overflow: auto">
            <el-tree
                ref="treeData"
                :data="treeData"
                show-checkbox
                :default-expand-all="expandAll"
                :expand-on-click-node="false"
                node-key="id"
                @node-click="nodeClick"
                highlight-current
                :filter-node-method="filterNode"
                @node-expand="nodeExpand"
                @node-collapse="nodeCollapse"
                :default-expanded-keys="expandArr"
                :props="defaultProps">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span v-if="data.status">{{ node.label }}</span>
              <span v-else style="color: #999;">{{ data.label }}--(隐藏)</span>
              <span>
                 <el-popover
                     placement="left"
                     width="200"
                     @show="show(data.id)"
                     :open-delay="200"
                     :close-delay="200"
                     trigger="hover">
                  <el-descriptions title="区域信息" size="medium" :column="1">
                      <el-descriptions-item label="名称">{{ showFormData.name }}</el-descriptions-item>
                      <el-descriptions-item label="管理人">{{ showFormData.manage }}</el-descriptions-item>
                      <el-descriptions-item label="管理人电话">{{ showFormData.managePhone }}</el-descriptions-item>
                      <el-descriptions-item label="状态">
                         <el-tag v-if="showFormData.status">启用</el-tag>
                          <el-tag type="danger" v-else>禁用</el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="排序">{{ showFormData.sort }}</el-descriptions-item>
                      <el-descriptions-item label="备注">{{ showFormData.remark }}</el-descriptions-item>
                  </el-descriptions>
                 <el-link slot="reference" @click.stop="">详情</el-link>
                </el-popover>
                <el-link type="success" @click.stop="addRegion(data.id)">新增子机构</el-link>
                <el-link type="warning" @click.stop="edit(data.id)">修改</el-link>
                 <el-popconfirm
                     trigger="hover"
                     @confirm="del(data.id)"
                     title="确认删除，删除父级会删除其下所有子项，确认删除！！"
                 >
                <el-link type="danger" slot="reference" @click.stop="">删除</el-link>
              </el-popconfirm>
              </span>
          </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="14">
          <div class="c-title" v-if="common.id">{{ common.label }}--下机构</div>
          <div class="c-title" v-else>请点击左侧区域</div>
          <el-form :inline="true" @submit.native.prevent>
            <el-input
                placeholder="输入关键字进行过滤"
                v-model="p.name"
                clearable>
            </el-input>
          </el-form>
          <el-table
              ref="organTable"
              :data="organData"
              style="width: 100%"
              highlight-current-row
              max-height="450">
            <el-table-column type="selection" width="40" align="center"></el-table-column>
            <el-table-column
                prop="name"
                min-width="60"
                label="机构名称">
            </el-table-column>
            <el-table-column
                min-width="80"
                label="所属区域">
              <template slot-scope="scope">
                <el-tag>{{ scope.row.regionDTO.name }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
                prop="manage"
                min-width="60"
                label="管理人">
            </el-table-column>
            <el-table-column
                prop="managePhone"
                min-width="60"
                :show-overflow-tooltip="true"
                label="管理人号码">
            </el-table-column>
            <el-table-column
                min-width="60"
                label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status" style="color: green">启用</span>
                <span v-else style="color: red">禁用</span>
              </template>
            </el-table-column>
            <el-table-column
                prop="remark"
                min-width="60"
                label="备注">
            </el-table-column>
            <el-table-column
                fixed="right"
                min-width="80"
                label="操作">
              <template slot-scope="scope">
                <el-popover
                    placement="left"
                    width="300"
                    @show="showOrgan(scope.row.id)"
                    :open-delay="200"
                    :close-delay="200"
                    trigger="hover">
                  <el-descriptions title="机构信息" size="medium" :column="1">

                    <el-descriptions-item label="名称">{{ showOrganData.name }}</el-descriptions-item>
                    <el-descriptions-item label="所属区域">
                      <el-tag v-if="showOrganData.regionDTO">{{ showOrganData.regionDTO.name }}</el-tag>
                      <el-tag v-else></el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="管理人">{{ showOrganData.manage }}</el-descriptions-item>
                    <el-descriptions-item label="管理人电话">{{ showOrganData.managePhone }}</el-descriptions-item>
                    <el-descriptions-item label="机构类型">
                      <el-tag>{{ showOrganData.typeName }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                      <el-tag v-if="showOrganData.status">启用</el-tag>
                      <el-tag type="danger" v-else>禁用</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="排序">{{ showOrganData.sort }}</el-descriptions-item>
                    <el-descriptions-item label="备注">{{ showOrganData.remark }}</el-descriptions-item>
                  </el-descriptions>
                  <el-button slot="reference" type="text">查看</el-button>
                </el-popover>

              </template>
            </el-table-column>
          </el-table>
          <div class="page-box">
            <el-pagination background
                           layout="total, prev, pager, next, sizes, jumper"
                           :current-page.sync="p.current"
                           :page-size.sync="p.size"
                           :total="p.total"
                           :page-sizes="[10, 20, 30, 40, 50, 100]"
                           @current-change="f5()"
                           @size-change="f5()">
            </el-pagination>
          </div>
        </el-col>
      </el-row>

    </div>
  </div>
</template>

<script>
let PATH = "/region"
let expandTag = "region"
module.exports = {
  components: {},
  watch: {
    regionKey: function (val) {
      this.$refs['treeData'].filter(val);
    },
    'p.name': function () {
      this.f5Organ()
    },
    showChildren: function () {
      this.f5Organ()
    }
  },
  data() {
    return {
      expandAll: sa.getItem(expandTag),
      showChildren: true,
      expandArr: [],
      common: {
        id: '',
        label: ''
      },
      disFlag: false,
      regionKey: '',
      formData: {
        pid: '0',
        name: undefined,
        manage: undefined,
        managePhone: undefined,
        status: true,
        sort: 0,
        remark: undefined,
      },
      rules: {
        pid: [{
          required: true,
          message: '请至少选择一个上级区域',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入区域名称',
          trigger: 'blur'
        }],
        manage: [{
          required: true,
          message: '请输入管理人姓名',
          trigger: 'blur'
        }],
        managePhone: [{
          required: true,
          message: '请输入管理人号码',
          trigger: 'blur'
        }],
        sort: [{
          required: true,
          message: '排序',
          trigger: 'blur'
        }],
        remark: [],
      },
      pidOptions: [],
      pidProps: {
        "multiple": false,
        "expandTrigger": 'hover',
        "label": "label",
        "value": "value",
        "children": "children",
        "checkStrictly": true,
        "emitPath": false
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      showFormData: {
        pid: '',
        name: undefined,
        manage: undefined,
        managePhone: undefined,
        status: true,
        sort: 0,
        remark: undefined,
      },
      organData: [],
      treeData: [],
      showOrganData: {},
      p: {
        // 搜索条件
        name: '',
        current: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: ''
    }
  },
  methods: {
    f5Organ() {
      sa.ajax(PATH + '/get-organ-by-region-id', {
            id: this.common.id,
            ...this.p,
            showChildren: this.showChildren
          },
          (res) => {
            this.organData = res.data
            this.p.total = res.dataCount
          }, {type: 'get'})
    },
    nodeClick(data) {
      this.common = data
      this.f5Organ()
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    setAllFold() { // 折叠所有节点
      this.expandArr = []
      sa.setItem(expandTag, false)
      this.expandAll= false
      let tree = this.$refs['treeData'];
      for (let i = 0; i < tree.store._getAllNodes().length; i++) {
        tree.store._getAllNodes()[i].expanded = false;
      }
    },
    setAllExpand() { // 展开所有节点
      this.expandArr = []
      sa.setItem(expandTag, true)
      this.expandAll= true
      let tree = this.$refs['treeData'];
      for (let i = 0; i < tree.store._getAllNodes().length; i++) {
        tree.store._getAllNodes()[i].expanded = true;
      }
    },
    nodeExpand(data) {
      let arr = this.expandArr
      arr.push(data.id)
      this.expandArr = arr
    },
    nodeCollapse(data) {
      let arr = this.expandArr
      arr.splice(arr.indexOf(data.id), 1)
      this.expandArr = arr
    },
    delAll() {
      let selects = this.$refs['roleTable'].selection
      if (selects.length === 0) return sa.error('请至少勾选一条数据')
    },
    userOpen() {
      sa.ajax(PATH + "/user-list", {}, (res) => {
        this.transferData = res.data
        this.value = this.userData.map(i => i.id)
      }, {msg: null, type: 'get'})
    },
    onOpen() {
      sa.ajax(PATH + "/parent-list", {}, (res) => {
        this.pidOptions = res.data
      }, {type: 'get', msg: null})
    },
    onClose() {
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.dialogVisible = false
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        sa.ajax(PATH + "/save-or-update", this.formData, (res) => {
          sa.alert(res.msg, () => {
            this.f5();
            this.close()
          })
        }, {})
      })
    },
    showOrgan(id) {
      sa.ajax(PATH + '/get-organ', {id: id}, (res) => {
        this.showOrganData = res.data
      }, {type: 'get', msg: null})
    },
    show(id) {
      sa.ajax(PATH + '/get', {id: id}, (res) => {
        this.showFormData = res.data
      }, {type: 'get', msg: null})
    },
    edit(id) {
      this.dialogTitle = '编辑区域'
      this.dialogVisible = true
      this.disFlag = false;
      sa.ajax(PATH + '/get', {id: id}, (res) => {
        this.formData = res.data
      }, {msg: null, type: 'get'})
    },
    addRegion(id) {
      this.dialogTitle = '新增区域'
      this.dialogVisible = true
      this.disFlag = true;
      this.formData.pid = id
    },
    del(id) {
      sa.ajax(PATH + '/del', {id: id}, (res) => {
        sa.alert(res.msg, () => {
          this.f5()
        })
      }, {type: 'get', msg: null})
    },
    f5() {
      sa.ajax(PATH + '/list', {name: this.regionKey}, (res) => {
        this.treeData = res.data;
      }, {type: 'get'})
    }
  },
  mounted() {

  },
  created() {
    this.f5()
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
